package handlers

import (
	"context"
	"ourplansystem/server/ent"
	"ourplansystem/server/ent/schedule"
	"ourplansystem/server/models"
	"strconv"
	"time"

	"github.com/gofiber/fiber/v2"
)

// ScheduleHandler 日程处理器
type ScheduleHandler struct {
	client *ent.Client
}

// NewScheduleHandler 创建日程处理器
func NewScheduleHandler(client *ent.Client) *ScheduleHandler {
	return &ScheduleHandler{client: client}
}

// CreateScheduleRequest 创建日程请求
type CreateScheduleRequest struct {
	Title       string `json:"title"`
	Description string `json:"description"`
	Deadline    string `json:"deadline"` // 格式: 2006-01-02 15:04:05
	Category    string `json:"category"`
	CreatorID   int64  `json:"creator_id"`
}

// UpdateScheduleRequest 更新日程请求
type UpdateScheduleRequest struct {
	Title       string `json:"title"`
	Description string `json:"description"`
	Deadline    string `json:"deadline"`
	Category    string `json:"category"`
	Status      string `json:"status"`
}

// GetSchedules 获取所有未删除的日程
func (h *ScheduleHandler) GetSchedules(c *fiber.Ctx) error {
	ctx := context.Background()
	schedules, err := h.client.Schedule.Query().
		Where(schedule.DeletedAtIsNil()).
		WithCreator().
		All(ctx)
	if err != nil {
		return models.InternalServerError(c, "获取日程列表失败")
	}

	return models.Success(c, schedules)
}

// GetSchedule 获取单个日程
func (h *ScheduleHandler) GetSchedule(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的日程ID")
	}

	schedule, err := h.client.Schedule.Query().Where().WithCreator().First(ctx)
	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "日程不存在")
		}
		return models.InternalServerError(c, "获取日程失败")
	}

	_ = id
	return models.Success(c, schedule)
}

// CreateSchedule 创建日程
func (h *ScheduleHandler) CreateSchedule(c *fiber.Ctx) error {
	ctx := context.Background()
	var req CreateScheduleRequest
	if err := c.BodyParser(&req); err != nil {
		return models.BadRequest(c, "请求参数错误")
	}

	if req.Title == "" {
		return models.BadRequest(c, "标题不能为空")
	}

	if req.CreatorID == 0 {
		return models.BadRequest(c, "创建者ID不能为空")
	}

	// 解析截止日期
	deadline, err := time.Parse("2006-01-02 15:04:05", req.Deadline)
	if err != nil {
		return models.BadRequest(c, "截止日期格式错误，应为: 2006-01-02 15:04:05")
	}

	builder := h.client.Schedule.
		Create().
		SetTitle(req.Title).
		SetDeadline(deadline).
		SetCreatorID(req.CreatorID)

	if req.Description != "" {
		builder.SetDescription(req.Description)
	}

	if req.Category != "" {
		builder.SetCategory(req.Category)
	}

	schedule, err := builder.Save(ctx)
	if err != nil {
		return models.InternalServerError(c, "创建日程失败")
	}

	return models.SuccessWithMessage(c, "创建成功", schedule)
}

// UpdateSchedule 更新日程
func (h *ScheduleHandler) UpdateSchedule(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的日程ID")
	}

	var req UpdateScheduleRequest
	if err := c.BodyParser(&req); err != nil {
		return models.BadRequest(c, "请求参数错误")
	}

	builder := h.client.Schedule.UpdateOneID(id)

	if req.Title != "" {
		builder.SetTitle(req.Title)
	}

	if req.Description != "" {
		builder.SetDescription(req.Description)
	}

	if req.Deadline != "" {
		deadline, err := time.Parse("2006-01-02 15:04:05", req.Deadline)
		if err != nil {
			return models.BadRequest(c, "截止日期格式错误")
		}
		builder.SetDeadline(deadline)
	}

	if req.Category != "" {
		builder.SetCategory(req.Category)
	}

	if req.Status != "" {
		builder.SetStatus(req.Status)
	}

	schedule, err := builder.Save(ctx)
	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "日程不存在")
		}
		return models.InternalServerError(c, "更新日程失败")
	}

	return models.SuccessWithMessage(c, "更新成功", schedule)
}

// DeleteSchedule 软删除日程
func (h *ScheduleHandler) DeleteSchedule(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的日程ID")
	}

	// 软删除：设置 deleted_at 为当前时间
	now := time.Now()
	_, err = h.client.Schedule.UpdateOneID(id).
		SetDeletedAt(now).
		Save(ctx)

	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "日程不存在")
		}
		return models.InternalServerError(c, "删除日程失败")
	}

	return models.SuccessWithMessage(c, "删除成功", nil)
}

// GetDeletedSchedules 获取所有已删除的日程（回收站）
func (h *ScheduleHandler) GetDeletedSchedules(c *fiber.Ctx) error {
	ctx := context.Background()
	schedules, err := h.client.Schedule.Query().
		Where(schedule.DeletedAtNotNil()).
		WithCreator().
		All(ctx)
	if err != nil {
		return models.InternalServerError(c, "获取已删除日程失败")
	}

	return models.Success(c, schedules)
}

// RestoreSchedule 恢复已删除的日程
func (h *ScheduleHandler) RestoreSchedule(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的日程ID")
	}

	// 恢复：清空 deleted_at
	_, err = h.client.Schedule.UpdateOneID(id).
		ClearDeletedAt().
		Save(ctx)

	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "日程不存在")
		}
		return models.InternalServerError(c, "恢复日程失败")
	}

	return models.SuccessWithMessage(c, "恢复成功", nil)
}

// PermanentDeleteSchedule 永久删除日程
func (h *ScheduleHandler) PermanentDeleteSchedule(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的日程ID")
	}

	err = h.client.Schedule.DeleteOneID(id).Exec(ctx)
	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "日程不存在")
		}
		return models.InternalServerError(c, "永久删除日程失败")
	}

	return models.SuccessWithMessage(c, "永久删除成功", nil)
}
